package com.personalblog.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.personalblog.po.Blog;
import com.personalblog.service.BlogService;
import com.personalblog.service.TagService;
import com.personalblog.service.TypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author jxau_scf
 * @date 2021/3/29 - 16:28
 */
@Controller
public class IndexController {
    @Autowired
    private BlogService blogService;
    @Autowired
    private TypeService typeService;
    @Autowired
    private TagService tagService;

    @GetMapping("/")
    public String index(@RequestParam(defaultValue = "1") int page, Model model){
        String orderBy = "blog_update_time desc";
        PageHelper.startPage(page,5,orderBy);
        List<Blog> blogList = blogService.findBlogs();
        PageInfo pageInfo = new PageInfo(blogList);
        model.addAttribute("pageInfo",pageInfo);
        model.addAttribute("types",typeService.findTypesFetchBlogs());
        model.addAttribute("tags",tagService.findTagsFetchBlogs());
        model.addAttribute("recommendBlogs",blogService.findBlogsOrderByUpdateTime(5));
        return "index";
    }

    @PostMapping("/search")
    public String search(@RequestParam String query, Model model){
        PageHelper.startPage(1,500);
        List<Blog> blogList = blogService.findBlogsByKeywordQuerySearch(query);
        PageInfo pageInfo = new PageInfo(blogList);
        model.addAttribute("pageInfo", pageInfo);
        model.addAttribute("query", query);
        return "search";
    }

    @GetMapping("/blog/{id}")
    public String blog(@PathVariable int id, Model model){
        model.addAttribute("blog",blogService.getAndConvert(id));
        return "blog";
    }

    @GetMapping("/footer/newblogs")
    public String newblogs(Model model){
        model.addAttribute("newblogs", blogService.findBlogsOrderByUpdateTime(3));
        return "_fragments :: newblogList";
    }

}
